# -*- coding: utf-8 -*-
import yaml, allure
from Config.LOG import Log
from Config.Pages.BasePages import BasePage
import requests

LOG = Log()
log = LOG.log2()
BasePage = BasePage()


def yaml_read(FileName):
    """
    读取yaml文件
    FileName:yaml文件名称，不需要传文件后缀
    :return:
    """
    with allure.step(f"打开yaml文件：{FileName}"):
        try:
            # # 获取当前脚本所在文件夹路径
            # curPath = os.path.dirname(os.path.realpath(__file__))
            # # 获取yaml文件路径
            # yamlPath = os.path.join(curPath, f"{FileName}.yaml")

            yamlPath = BasePage.get_file_path(f"{FileName}.yaml")
            # open方法打开直接读出来
            f = open(yamlPath, 'r', encoding='utf-8')
            cfg = f.read()  # 字符串格式的所有yaml数据
            d = yaml.load(cfg, Loader=yaml.FullLoader)  # 用load方法转字典
            return d  # 返回字典格式的yaml数据
        except Exception as e:
            log.error(e)


def yaml_request(FileName):
    """
    request读取Yaml文件里面的参数；
    Yaml文件中：接口需要列出接口所有模块（需要传的）
    注：Yaml文件中只存在一个接口
    :param FileName: 文件名称（不带后缀）
    :return:
    """
    with allure.step(f"执行{FileName}.yaml 文件中接口"):
        try:
            req_param = yaml_read(FileName)
            data_dict = req_param.copy()
            log.info(f"请求参数：{data_dict}")

            method = data_dict.get('method')
            if method is None:
                log.error("无接口类型")
                raise ("无接口类型")
            url = data_dict.get('url')
            if url is None:
                log.error("无接口网址")
                raise ("无接口网址")

            params = data_dict.get('params')
            data = data_dict.get('data')
            headers = data_dict.get('headers')
            cookies = data_dict.get('cookies')
            files = data_dict.get('files')
            auth = data_dict.get('auth')
            timeout = data_dict.get('timeout')
            allow_redirects = data_dict.get('allow_redirects', default=True)

            proxies = data_dict.get('proxies')
            hooks = data_dict.get('hooks')
            stream = data_dict.get('stream')
            verify = data_dict.get('verify')
            cert = data_dict.get('cert')
            json = data_dict.get('json')
            with requests.sessions.session() as session:
                return session.request(method,
                                       url,
                                       params=params,
                                       data=data,
                                       headers=headers,
                                       cookies=cookies,
                                       files=files,
                                       auth=auth,
                                       timeout=timeout,
                                       allow_redirects=allow_redirects,
                                       proxies=proxies,
                                       hooks=hooks,
                                       stream=stream,
                                       verify=verify,
                                       cert=cert,
                                       json=json
                                       )
        except Exception as e:
            log.error(e)
            raise e


def yaml_request2(FileName):
    """
    request读取Yaml文件里面的参数；
    Yaml文件中：接口需要列出接口所有模块（需要传的）
    :param FileName: 文件名称（不带后缀）
    :return:
    """
    with allure.step(f"执行{FileName}.yaml 文件中接口"):

        try:
            req_param = yaml_read(FileName)
            log.info(f"请求参数：{req_param}")
            requests.request(*req_param)
        except Exception as e:
            log.error(e)
            raise e
